package cn.joyfulmedia.mis.utils;

import com.alibaba.fastjson.JSON;
import cn.joyfulmedia.common.constant.Const;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author daijiacheng
 * @date 03/04/2018
 */
public class WordUtil {
    public final static String ANSWER_TITLE = "【答案】";
    public final static String EXAM_POINT_TITLE = "【考点】";
    public final static String ANALYSIS_TITLE = "【解析】";
    public final static String DIFFICULTY_TITLE = "【难度】";
    public final static String SPLIT_SYMBOL = "】";
    public final static String A_OPTION_AND_DOT = "A.";
    public final static String B_OPTION_AND_DOT = "B.";
    public final static String C_OPTION_AND_DOT = "C.";
    public final static String D_OPTION_AND_DOT = "D.";
    public final static String E_OPTION_AND_DOT = "E.";
    public final static String F_OPTION_AND_DOT = "F.";

    public final static String A_OPTION_AND_DOT_ZH_CN = "A。";
    public final static String B_OPTION_AND_DOT_ZH_CN = "B。";
    public final static String C_OPTION_AND_DOT_ZH_CN = "C。";
    public final static String D_OPTION_AND_DOT_ZH_CN = "D。";
    public final static String E_OPTION_AND_DOT_ZH_CN = "E。";
    public final static String F_OPTION_AND_DOT_ZH_CN = "F。";

    public final static String A_OPTION = "A.";
    public final static String B_OPTION = "B[.]";
    public final static String C_OPTION = "C[.]";
    public final static String D_OPTION = "D[.]";
    public final static String E_OPTION = "E[.]";
    public final static String F_OPTION = "F[.]";
    private static final Logger logger = LoggerFactory.getLogger(WordUtil.class);

    public static void main(String[] args) {

        String test = "A.标准化B.信 度 C.效度 D.常模E.量度";
        if (test.contains("  ")) {
            System.out.println("包含两个或两个以上空格");
        }
        List<String> splitList = splitOptions(test);
        System.out.println(JSON.toJSONString(splitList));
        System.out.println(splitList.size());
        String[] testSplit = test.split(C_OPTION, 2);
        for (String tmp: testSplit) {
            System.out.println(tmp);
        }
    }

    public static boolean matchBCD(String param) {
        if (param.contains(B_OPTION_AND_DOT)) {
            if (param.contains(C_OPTION_AND_DOT)) {
                if (param.contains(D_OPTION_AND_DOT)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean containTwoOptionKey(String param) {
        int count = 0;
        if (param.contains(A_OPTION_AND_DOT)) {
            count++;
        }
        if (param.contains(B_OPTION_AND_DOT)) {
            count++;
        }
        if (param.contains(C_OPTION_AND_DOT)) {
            count++;
        }
        if (param.contains(D_OPTION_AND_DOT)) {
            count++;
        }
        if (param.contains(E_OPTION_AND_DOT)) {
            count++;
        }
        if (param.contains(F_OPTION_AND_DOT)) {
            count++;
        }
        return count >= 2;
    }

    // 拆封选项数据
    public static List<String> splitOptions(String param) {
        List<String> result = new ArrayList<>();

        String[] tmpStrArr1 = param.split(B_OPTION, 2);
        String aOption = tmpStrArr1[0];
        if (aOption.contains(A_OPTION)) {
            int tmpIndex = aOption.indexOf(A_OPTION);
            aOption = aOption.substring(tmpIndex+2);
        }
        result.add(aOption.trim());

        String remainderStr = tmpStrArr1[1];
        String[] tmpStrArr2 = remainderStr.split(C_OPTION, 2);
        String bOption = tmpStrArr2[0];
        result.add(bOption.trim());
        remainderStr = tmpStrArr2[1];
        String[] tmpStrArr3 = remainderStr.split(D_OPTION, 2);
        String cOption = tmpStrArr3[0];
        result.add(cOption.trim());

        remainderStr = tmpStrArr3[1];
        if (remainderStr.contains(E_OPTION_AND_DOT)) {
            String[] tmpStrArr4 = remainderStr.split(E_OPTION);
            result.add(tmpStrArr4[0].trim());

            remainderStr = tmpStrArr4[1];
            if (remainderStr.contains(F_OPTION_AND_DOT)) {
                String[] tmpStrArr5 = remainderStr.split(F_OPTION);
                result.add(tmpStrArr5[0].trim());
                result.add(tmpStrArr5[1].trim());
            } else {
                result.add(remainderStr.trim());
            }
        } else {
            result.add(remainderStr.trim());
        }
        return result;
    }

    // 拆封答案、考点、解析数据
    public static String splitTitle(String param) {
        String[] tmpAnswerArr = param.split(SPLIT_SYMBOL);
        if (tmpAnswerArr.length > 1) {
            return tmpAnswerArr[1];
        }
        return "";
    }

    public static Integer parseItemType(String param) {
        if (param.contains("单项选择题，")) {
            return Const.SINGLE_CHOICE;
        } else if (param.contains("多项选择题，")) {
            return Const.MULTI_CHOICE;
        } else if (param.contains("判断题，")) {
            return Const.TRUE_OR_FALSE;
        } else if (param.contains("简答题，")) {
            return Const.SHORT_ANSWER_QUESTION;
        } else if (param.contains("综合分析题，")) {
            return Const.CASE_ANALYSIS_QUESTION;
        } else if (param.contains("公文筐测验，")) {
            return Const.OFFICIAL_DOCUMENT_PROCESSING_TEST;
        } else if (param.contains("计算题，")) {
            return Const.CALC_QUESTION;
        }
        return null;
    }

    public static Integer parseItemScore(String param) {
        String[] tmpStrArray = param.split("，");
        if (tmpStrArray.length > 1) {
            String tmpScoreStr = tmpStrArray[1].substring(0, tmpStrArray[1].indexOf("分"));
            System.out.println("---------截取的分数------" + tmpScoreStr);
            return Integer.parseInt(tmpScoreStr.trim());
        } else {
            logger.error("该类型题目没有设置每天分值：" + param);
        }
        return 0;
    }

    public static List<Integer> parseItemScoreList(String param) {
        String[] tmpStrArray = param.split("，");
        int leng = tmpStrArray.length;
        if (leng > 1) {
            List<Integer> result = new ArrayList<>();
            for (int i = 1; i < leng; i++) {
                String tmpScoreStr = tmpStrArray[i].substring(0, tmpStrArray[1].indexOf("分"));
                tmpScoreStr = tmpScoreStr.trim();
                if (StringUtils.isNotBlank(tmpScoreStr)) {
                    Integer tmpScore = Integer.parseInt(tmpScoreStr);
                    result.add(tmpScore);
                }
            }
            System.out.println("---------截取的分数------" + JSON.toJSONString(result));
            return result;
        } else {
            logger.error("该类型题目没有设置每天分值：" + param);
        }
        return new ArrayList<>();
    }

    /**
     * 读取word文件内容
     *
     * @param path
     * @return buffer
     */

    public static BufferedReader readWord(String path) {
        String buffer = "";
        try {
            if (path.endsWith(".doc")) {
                InputStream is = new FileInputStream(new File(path));
                WordExtractor ex = new WordExtractor(is);
                buffer = ex.getText();
                ex.close();
            } else if (path.endsWith("docx")) {
                OPCPackage opcPackage = POIXMLDocument.openPackage(path);
                POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
                buffer = extractor.getText();
                extractor.close();
            } else {
                System.out.println("此文件不是word文件！");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotBlank(buffer)) {
            String str = "";
            ByteArrayInputStream stream = new ByteArrayInputStream(buffer.getBytes());
            InputStreamReader isr = new InputStreamReader(stream);// InputStreamReader 是字节流通向字符流的桥梁,
            BufferedReader br = new BufferedReader(isr);// 从字符输入流中读取文件中的内容,封装了一个new InputStreamReader的对象
            return br;
        }
        return null;
    }

    // 上传文件写入新的文件
    public static File writeFile(MultipartFile Mfile, String fileName) {
        //把spring文件上传的MultipartFile转换成CommonsMultipartFile类型
        CommonsMultipartFile cf = (CommonsMultipartFile) Mfile; //获取本地存储路径
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        System.out.println("路径：" + path);
        path = path.replace("/classes", "");
        String uri = path + "static/fileupload/";

        File file = new File(uri);
        //创建一个目录 （它的路径名由当前 File 对象指定，包括任一必须的父路径。）
        if (!file.exists()) {
            file.mkdirs();
        }
        ;
        //新建一个文件
        File file1 = new File(uri + fileName);
        //将上传的文件写入新建的文件中
        try {
            cf.getFileItem().write(file1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file1;
    }
}
